package com.wufun.overseas.main.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.view.View;

import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;


import com.wufun.overseas.R;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.models.bean.LiveUploadData;
import com.wufun.overseas.utils.ImageCompressor;
import com.wufun.overseas.utils.JsonMapper;
import com.wufun.overseas.utils.NetWorkUtils;
import com.wufun.overseas.utils.TCUploadHelper;
import com.wufun.overseas.utils.ToastUtils;
import com.wufun.overseas.view.LJWebView;
import com.wufun.overseas.view.LodingDialog;


import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by tangbl on 2017/12/10 0010.
 */

public class FeedBackActivity extends MyActivity {

    @Bind(R.id.webview)
    LJWebView webView;
    @Bind(R.id.iv_close)
    ImageView iv_close;
    @Bind(R.id.iv_refresh)
    ImageView iv_refresh;
    private String url;
    private Activity context;
    private Handler mHandler = new Handler();
    private boolean isError = false;
    private TCUploadHelper mUploadHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        ButterKnife.bind(this);
        rootBarRl.setVisibility(View.GONE);
        context = this;
        url = "http://anv1frapi-inter.papa91.com/game_feedback/index?emu_type=" + getResources().getString(R.string.app_flag);
//        url = "http://apphd.papa91.com/papa_help";
        lodeWebView(url);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //刷新
                lodeWebView(url);
            }
        });


    }

    private void lodeWebView(String url) {
        if (webView == null) return;
        webView.setVisibility(View.VISIBLE);
        webView.setBarHeight(getResources().getDimensionPixelOffset(R.dimen.dimen_dp_3));
        webView.setClickable(true);
        webView.setUseWideViewPort(true);
        webView.setSupportZoom(false);
        webView.setBuiltInZoomControls(false);
        webView.setJavaScriptEnabled(true);
        webView.setCacheMode(WebSettings.LOAD_DEFAULT);

        webView.setWebViewClient(new WebViewClientXY(FeedBackActivity.this));
        webView.addJavascriptInterface(new WebJSPInterfaceMethedBean());
//        webView.addJavascriptInterfacewufan(new WebJSPInterfaceMethedBeanWufan());
        webView.loadUrl(url);
    }

    private List<String> uploadFilesSuccessUrl = new ArrayList<>();


    /**
     * 去选择图片
     */
    public void goMyAlbumActivity4PickPic() {
        Intent intent = new Intent(this, MyAlbumActivity.class);
        Bundle bundle = new Bundle();
        uploadFilesSuccessUrl.clear();
        mSelectedImages.clear();
        bundle.putSerializable(MyAlbumActivity.KEY_SELECTED_IMAGES, (Serializable) mSelectedImages);
        intent.putExtras(bundle);
        startActivityForResult(intent, MyAlbumActivity.REQUEST_CODE_ALBUM);
    }

    Iterator<String> iterator;
    private boolean uploadFiles = false;
    private List<String> uploadImages = new ArrayList<>();

    private void uploadImage() {

        iterator = uploadImages.iterator();
        if (iterator != null && iterator.hasNext()) {
            String path = iterator.next();
//            mUploadHelper.uploadCover(path, 1 + "", "");   //没用uid 和token
            iterator.remove();
        } else {
            LiveUploadData data = new LiveUploadData();
            data.setCode(1);
            if (uploadFilesSuccessUrl.size() == 0) {
                data.setCode(0);
            } else {
                try {
                    data.setData(uploadFilesSuccessUrl.toArray(new String[uploadFilesSuccessUrl.size()]));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String json = JsonMapper.getInstance().toJson(data);
            webView.loadUrl("javascript:papaChoiceAndUploadImg('" + json + "')");
        }
    }

    private void finishM() {
//        Activity activity = IntentUtil.getInstance().getSplashActivity();
//        if (activity != null) {
//            activity.finish();
//            IntentUtil.getInstance().setSplashActivity(null);
//            Intent intent = new Intent();
//            intent.setClass(activity, com.join.mgps.activity.MGMainActivity_.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//            startActivity(intent);
//        }
        finish();
    }

    public class WebJSPInterfaceMethedBean {

        /**
         * 当按返回键时返回到指定页面
         *
         * @param
         */
        @JavascriptInterface
        public void goBackUrl(final String url) {
            mHandler.post(new Runnable() {
                public void run() {
                    if ("".equals(url)) {
                        finishM();
                    } else {
                        webView.loadUrl(url);
                    }
                }
            });
        }

        /**
         * tost字符串
         */
        @JavascriptInterface
        public void toastText(final String message) {
            mHandler.post(new Runnable() {
                public void run() {
                    ToastUtils.getInstance(context).showToastSystem(message);
                }
            });
        }


        /**
         * 去选择要上传的图片
         */
        @JavascriptInterface
        public void goChoiceUploadImage() {
            mHandler.post(new Runnable() {
                public void run() {
                    goMyAlbumActivity4PickPic();
                }
            });
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            //暂时删除，主项目有ShareWebActivity
        }
        if (requestCode == MyAlbumActivity.REQUEST_CODE_ALBUM) {
            if (mSelectedImages == null) mSelectedImages = new ArrayList<String>();
            mSelectedImages.clear();
            mSelectedImages.addAll(getImagesFromAlbum(data));
            ImageCompressor.getInstance().pullCompressState();
//            ImageCompressor.getInstance().compressImage(getApplicationContext(), path, addTask);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.loadUrl("javascript:papaActivityOnResume()");
        if (webView != null) {
            try {
                webView.getWebView().getClass().getMethod("onResume").invoke(webView.getWebView(), (Object[]) null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        ImageCompressor.getInstance().addCompressListener(mCompressListener);

    }

    @Override
    protected void onPause() {
        if (webView != null) {
            try {
                webView.getWebView().getClass().getMethod("onPause").invoke(webView.getWebView(), (Object[]) null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        webView.loadUrl("");
        if (mCompressListener != null)
            ImageCompressor.getInstance().removeCompressListener(mCompressListener);
        super.onDestroy();
    }

    List<String> mSelectedImages = new ArrayList<>();
    private ImageCompressor.CompressListener mCompressListener = new ImageCompressor.CompressListener() {
        @Override
        public void onCompress(Boolean allFinished, Map<String, String> compressMap, Map<String, Integer> compressState) {
//            LogUtil_.logError("uploadData", allFinished + "   " + compressMap.size() + "  " + compressState.size());
            if (allFinished && mSelectedImages != null && mSelectedImages.size() != 0) {
                List<String> compressedList = new ArrayList<String>();
                for (int i = 0; i < mSelectedImages.size(); i++) {
                    String src = mSelectedImages.get(i);
                    int state = compressState.get(src);
                    String dest = compressMap.get(src);
                    if (state == 1) {
                        compressedList.add(dest);
                    }
                }

                togglePostSubmit(compressedList);

            } else {
                togglePostSubmit(null);
            }
        }

        private void togglePostSubmit(List<String> list) {
            //获得选择的图片之后开始上传
            if (list != null && list.size() > 0) {
//                LogUtil_.logError("uploadData", "  togglePostSubmit " + list.size());
                uploadImages.clear();
                uploadImages.addAll(list);
                showLoading("Uploading images");
                uploadImage();
                uploadFiles = true;
            }
        }
    };


    private List<String> getImagesFromAlbum(Intent intent) {
        if (intent == null || intent.getExtras() == null) return new ArrayList<String>();

        return (List<String>) intent.getExtras().get(MyAlbumActivity.KEY_SELECTED_IMAGES);
    }

    private class WebViewClientXY extends WebViewClient {
//        private Dialog progressDialog;

        public WebViewClientXY(Context context) {

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url2) {


            if (NetWorkUtils.isNetworkConnected(context)) {
                if (!url2.startsWith("weixin:")) {
                    if (url2.startsWith("http") || url2.startsWith("https") || url2.startsWith("file://")) {
                        url = url2;
                    } else {
                        try {
                            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url2)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return true;
                    }
                    return super.shouldOverrideUrlLoading(view, url2);

                } else {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url2)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
//                ToastUtils.getInstance(context).showToastSystem(getString(R.string.net_connect_failed));
                Toast.makeText(FeedBackActivity.this, "network", Toast.LENGTH_SHORT).show();
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url2, Bitmap favicon) {
            super.onPageStarted(view, url2, favicon);


            if (url2.startsWith("http") || url2.startsWith("https") || url2.startsWith("file://")) {
//                view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
                url = url2;//记录url
            }
//            showLoding();        // 暂时不要
        }

        @Override
        public void onPageFinished(WebView view, String url2) {
            super.onPageFinished(view, url2);
//            LogUtil_.logDebug(TAG, "onPageFinished() called." + url2);
            if (url2.startsWith("http") || url2.startsWith("https") || url2.startsWith("file://")) {
//                view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
                url = url2;//记录url
            }
            //显示默认的失败界面的url
            if (url.equals("data:text/html,chromewebdata") || isError) {
//                showLodingFailed();    //暂时不要yg
                return;
            }
            view.getSettings().setBlockNetworkImage(false);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
//            LogUtil_.logDebug(TAG, "onReceivedError() called." + failingUrl);
            isError = true;
            view.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
//            showLodingFailed();   //暂时不要yg
        }

    }


    public static Intent buildIntent(Context context, String title) {
        Intent intent = new Intent(context, FeedBackActivity.class);
        intent.putExtra("title", title);
        return intent;
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);
        setBarTitleTx(getIntent().getStringExtra("title"));
    }


}
